package com.jilefojing.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.manager.response.RecommendData;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.enums.ItemTypeEnumForSource;
import com.jilefojing.beans.enums.PlatformEnumForPublish;
import com.jilefojing.beans.enums.ProgressStatusForSource;
import com.jilefojing.beans.enums.StatusEnumForPublish;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.Recommend;
import com.jilefojing.beans.pojos.enhanced.EnhancedEAudio;
import com.jilefojing.beans.pojos.enhanced.EnhancedEVideo;
import com.jilefojing.beans.pojos.enhanced.EnhancedRecommend;
import com.jilefojing.beans.pojos.enhanced.base.BaseEnhanced;
import com.jilefojing.beans.query.EAudioQuery;
import com.jilefojing.beans.query.EVideoQuery;
import com.jilefojing.beans.query.RecommendQuery;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.beans.vo.UploadFile;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.controller.base.BaseController;
import com.jilefojing.controller.convent.CommonConvent;
import com.jilefojing.service.IEAudioService;
import com.jilefojing.service.IEVideoService;
import com.jilefojing.service.IRecommendService;
import com.jilefojing.service.ISourceService;
import com.jilefojing.util.Detect;

@Controller
@RequestMapping("recommend")
public class RecommendController extends BaseController {
	@Autowired
	private IRecommendService recommendService;
	@Autowired
	private ISourceService sourceService;
	@Autowired
	private IEVideoService eVideoService;
	@Autowired
	private IEAudioService eAudioService;

	@RequestMapping("add")
	public @ResponseBody ResponseData add(Recommend recommend, HttpServletRequest request) throws UserContextException {
		ResponseData responseData = new ResponseData();
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String startTimeStr = request.getParameter("startTimeStr");
			String endTimeStr = request.getParameter("endTimeStr");
			if (Detect.notEmpty(startTimeStr)) {
				recommend.setStartTime(df.parse(startTimeStr));
			}
			if (Detect.notEmpty(endTimeStr)) {
				recommend.setEndTime(df.parse(endTimeStr));
			}
			UploadFile coverUploadFile = null;
			try {
				coverUploadFile = super.getUploadFile("coverFile", (MultipartHttpServletRequest) request);
			} catch (Exception ex) {
				// 可忽略
			}

			UserContext userContext = super.getUserContext();
			recommend = recommendService.add(recommend, coverUploadFile, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		} catch (ParseException e) {
			responseData.setResponseEnum(ResponseEnum.UNKNOWN);
			responseData.setResponseMessage(e.getMessage());
		}
		return responseData;
	}

	@RequestMapping("add.html")
	public String toAddPage(short itemType, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();
		ItemTypeEnumForSource itemTypeEnumForSource = ItemTypeEnumForSource.getItemTypeEnumByCode(itemType);

		return "recommend/" + itemTypeEnumForSource.getItemClass().getSimpleName().toLowerCase() + "_add";
	}

	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public @ResponseBody ResponseData delete(@RequestParam("ids[]") ArrayList<Long> ids, HttpServletRequest request) {
		ResponseData responseData = new ResponseData();
		try {
			UserContext userContext = super.getUserContext();
			recommendService.deleteByIds(ids, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}
		return responseData;
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public @ResponseBody ResponseData update(Recommend recommend, String startTimeStr, String endTimeStr, HttpServletRequest request) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		ResponseData responseData = new ResponseData();
		try {
			UserContext userContext = super.getUserContext();

			recommend.setStartTime(df.parse(startTimeStr));
			recommend.setEndTime(df.parse(endTimeStr));

			recommend = recommendService.update(recommend, userContext);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		} catch (Exception e) {
			responseData.setResponseEnum(ResponseEnum.UNKNOWN);
			responseData.setResponseMessage(e.getMessage());
		}
		return responseData;
	}

	@RequestMapping("list")
	public @ResponseBody Map<String, Object> getRecommendList(Short itemType, String like_title, Short status, Short progressStatus, Short platform, HttpServletRequest request)
			throws UserContextException {
		UserContext userContext = super.getUserContext();

		int page = Integer.valueOf(request.getParameter("page"));
		int rows = Integer.valueOf(request.getParameter("rows"));

		String sortsStr = request.getParameter("sort");
		String ordersStr = request.getParameter("order");

		Pagination<EnhancedRecommend> pagination = new Pagination<EnhancedRecommend>(page, rows, true);
		if (!Detect.notEmpty(sortsStr)) {
			pagination.addOrder(new Order(Recommend.COLUMN_SORT, Order.ORDER_DESC)).addOrder(new Order(Recommend.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		} else {
			super.addSorts(sortsStr, ordersStr, Recommend.FIELD_SORT, Recommend.COLUMN_SORT, pagination);
			super.addSorts(sortsStr, ordersStr, Recommend.FIELD_UPDATETIME, Recommend.COLUMN_UPDATE_TIME, pagination);
		}

		RecommendQuery recommendQuery = new RecommendQuery();
		if (status != null && status > 0) {
			recommendQuery.setStatuses(Arrays.asList(new StatusEnumForPublish[] { StatusEnumForPublish.getStatusEnumByCode(status) }));
		}

		if (progressStatus != null && progressStatus > 0) {
			recommendQuery.setProgressStatuses(Arrays.asList(new ProgressStatusForSource[] { ProgressStatusForSource.getProgressStatusEnumByCode(progressStatus) }));
		}

		if (platform != null && platform > 0) {
			recommendQuery.setPlatforms(Arrays.asList(new PlatformEnumForPublish[] { PlatformEnumForPublish.getPlatformEnumByCode(platform) }));
		}
		if (itemType != null && itemType > 0) {
			ItemTypeEnumForSource itemTypeEnumForSource = ItemTypeEnumForSource.getItemTypeEnumByCode(itemType);
			recommendQuery.setItemTypes(Arrays.asList(new ItemTypeEnumForSource[] { itemTypeEnumForSource }));

			if (Detect.notEmpty(like_title)) {
				List<Long> itemIds = this.getItemIdsByLikeTitle(itemTypeEnumForSource, like_title, userContext);
				if (!Detect.notEmpty(itemIds)) {
					Map<String, Object> resultMap = new HashMap<String, Object>();
					resultMap.put("total", 0);
					resultMap.put("rows", new ArrayList<RecommendData>());
					return resultMap;
				}
				recommendQuery.setItemIds(itemIds);
			}
		}

		pagination = recommendService.getPagination(recommendQuery, pagination, userContext);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("total", pagination.getCount());
		List<RecommendData> recommendDatas = new ArrayList<RecommendData>();
		if (Detect.notEmpty(pagination.getItems())) {
			List<BaseEnhanced> enhancedItems = new ArrayList<BaseEnhanced>();
			for (EnhancedRecommend _EnhancedRecommend : pagination.getItems()) {
				enhancedItems.add(_EnhancedRecommend.getEnhancedItem());
			}
			enhancedItems = sourceService.appendEnhancedParent2EnhancedItems(enhancedItems, userContext);
			recommendDatas = CommonConvent.convent2RecommendDatas(pagination.getItems());
		}
		resultMap.put("rows", recommendDatas);

		return resultMap;
	}

	private List<Long> getItemIdsByLikeTitle(ItemTypeEnumForSource itemType, String like_title, UserContext userContext) {
		List<Long> itemIds = new ArrayList<Long>();
		@SuppressWarnings("rawtypes")
		Pagination pagination = null;
		if (itemType == ItemTypeEnumForSource.VIDEO) {
			EVideoQuery eVideoQuery = new EVideoQuery();
			eVideoQuery.setLike_title(like_title);
			pagination = eVideoService.getPagination(eVideoQuery, new Pagination<EnhancedEVideo>(1, Integer.MAX_VALUE, false), userContext);
		} else if (itemType == ItemTypeEnumForSource.AUDIO) {
			EAudioQuery eAudioQuery = new EAudioQuery();
			eAudioQuery.setLike_title(like_title);
			pagination = eAudioService.getPagination(eAudioQuery, new Pagination<EnhancedEAudio>(1, Integer.MAX_VALUE, false), userContext);
		} else {
			throw new IllegalArgumentException("[暂不支持此类型的标题查询]");
		}
		if (Detect.notEmpty(pagination.getItems())) {
			@SuppressWarnings("unchecked")
			List<BaseEnhanced> enhancedItems = (List<BaseEnhanced>) pagination.getItems();
			for (BaseEnhanced _BaseEnhanced : enhancedItems) {
				itemIds.add(_BaseEnhanced.getDynamicId());
			}
		}
		return itemIds;
	}

	@RequestMapping("list.html")
	public String toRecommendList(short itemType, HttpServletRequest request) throws UserContextException {
		UserContext userContext = super.getUserContext();
		ItemTypeEnumForSource itemTypeEnumForSource = ItemTypeEnumForSource.getItemTypeEnumByCode(itemType);

		return "recommend/" + itemTypeEnumForSource.getItemClass().getSimpleName().toLowerCase() + "_list";
	}
}
